@()(implicit session: Session)
@config.main("Synteny") {

    <style>

            .help-block {
                color: red;
            }

            .btn-primary {
                font-size: 12px;
                padding: 2px 2px 4px 2px;
                font-weight: bold;
            }

            .highcharts-menu-item {
                cursor: pointer;
                padding: 0.5em 1em;
                color: rgb(51, 51, 51);
                background: none;
                font-size: 11px;
                transition: background 250ms ease 0s, color 250ms ease 0s;
            }

            .highcharts-menu-item:hover {
                background-color: #0a53be;
                color: white;
            }

    </style>


    <div class="body-box">
        <div class="page-box">

            @config.subTitle("Synteny")

            <div class="main-body">


                @components.navUlComponents(Seq(("byBlocks", "Search Syntenic Blocks", ByBlocks),
                    ("byBlockId", "Search a Block By Block ID", ByBlockId),
                    ("bySpecies", "Dot Plot By Species", BySpecies),
                    ("byCircos", "Circos Plot By Species", CircosBySpecies)

                ), "byBlocks")



            </div>
        </div>
    </div>


    <script src="@routes.Assets.versioned("circos/d3.v3.min.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("circos/bam2x.circos.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("circos/test.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("blast/js/FileSaver.min.js")" type="text/javascript"></script>
    <script src="@routes.Assets.versioned("Highcharts-9.0.1/highcharts.js")" type ="text/javascript"></script>
    <script src="@routes.Assets.versioned("Highcharts-9.0.1/modules/boost.js")" type ="text/javascript"></script>
    <script src="@routes.Assets.versioned("Highcharts-9.0.1/modules/exporting.js")" type ="text/javascript"></script>

    <script>


            $(document).mousedown(function(event){
                let c = $(event.target).attr("class")
                let s =  $(".highcharts-contextmenu").is(":hidden");
                if(!s && c !== "highcharts-menu-item"){
                    $(".highcharts-contextmenu").hide()
                }
            });


            $(function () {
                getChr()
            //    getComparison()
                $("#species2").val("Camellia_lanceoleosa")
                $("#species2-1").val("Camellia_lanceoleosa")

                DisData()
                DisData2()
            })


            function Search() {

                let form = $("#blocksForm");
                let fv = form.data("formValidation");
                fv.validate();
                if (fv.isValid()) {
                    let index = MyTable.prototype.runningIcon();

                    $.ajax({
                        url: "@routes.BlockController.getComparisonResult",
                        type: "post",
                        data: $("#blocksForm").serialize(),
                        success: function (data) {

                            $("#result-box").empty();

                            let title = ""
                            let body = ""
                            $.each(data, (i, v) => {
                                let active1 = ""
                                let active2 = ""
                                if (i === 0) {
                                    active1 = "active"
                                    active2 = "show active"
                                }

                                title += `<li class="nav-item" role="presentation">
                                                <a class="nav-link ${active1}" id="${v.ref}-tab" data-toggle="tab" href="#${v.ref}" role="tab" aria-controls="${v.ref}" aria-selected="true">${v.title}</a>
                                          </li>`

                                body += `<div class="tab-pane fade  ${active2} " id="${v.ref}" role="tabpanel" aria-labelledby="${v.ref}-tab">

<div style="position: absolute;width: 1000px;text-align: right">
    <div class="download-btn" style="position: absolute;z-index: 1000;right:0;">

    <button type="button"><i class="fa fa-align-justify" style="color:#666666"></i> Save</button>


        <div class="highcharts-contextmenu" style="display: none;text-align: left" >
        <ul class="highcharts-menu" style="list-style: none; margin: 0px; padding: 5px 0px; box-shadow: rgb(136, 136, 136) 3px 3px 10px; border: 1px solid rgb(153, 153, 153); background: rgb(255, 255, 255);">
            <li class="highcharts-menu-item" onclick="DownloadSvg('${v.ref}-circos','png')" >Download PNG image</li>
<li class="highcharts-menu-item" onclick="DownloadSvg('${v.ref}-circos','jpeg')" >Download JPEG image</li>
<li class="highcharts-menu-item" onclick="DownloadSvg('${v.ref}-circos','pdf')" >Download PDF document</li>
<li class="highcharts-menu-item" onclick="DownloadSvgFn('${v.ref}-circos')" >Download SVG vector image</li></ul></div>

    </div> </div>


                                             <div id="${v.ref}-circos"></div>
                                             <table id="${v.ref}-table" class="table table-bordered" data-pagination="true" data-page-list="[10, 25, 50, 100]">
                                                 <thead>
                                                    <tr>
                                                        <th data-field='name' data-formatter="GetBlock">Block ID</th>
                                                        <th data-field='s1' data-formatter="GetSpecies1">Species1 (location)</th>
                                                        <th data-field='s2' data-formatter="GetSpecies2">Species2 (location)</th>
                                                        <th data-field='score' >Score</th>
                                                        <th data-field='eValue' >E_Value</th>
                                                        <th data-field='n' >N</th>
                                                    </tr>
                                                </thead>
                                            </table>
                                        </div>`

                            })

                            let html = `<ul class="nav nav-tabs" role="tablist">${title}</ul><div class="tab-content">${body}</div>`
                            $("#result-box").html(html);

                            $(".download-btn").click(function () {
                                let s = $(this).find(".highcharts-contextmenu").is(":hidden");

                                if (s) {
                                    $(this).find(".highcharts-contextmenu").show()
                                } else {
                                    $(this).find(".highcharts-contextmenu").hide()
                                }

                            })

                            $.each(data, (i, v) => {
                                let datas = [
                                    {
                                        "canvas": v.ref + "-circos",
                                        "ideoCollection": v.result.collection,
                                        "linkCollection": v.result.ur
                                    }
                                ];
                                circos(datas)
                                $("#" + v.ref + "-table").bootstrapTable({data: v.result.table})
                            })

                            const $result = $("#b-result");
                            $result.show()
                            let target_top = $result.offset().top - 80;
                            $("html,body").animate({scrollTop: target_top}, 800);

                            layer.close(index)
                        }
                    });
                }

            }

            function DownloadSvgFn(svg) {
                let svgs = "<svg xmlns=\"http://www.w3.org/2000/svg\"      xmlns:xlink=\"http://www.w3.org/1999/xlink\"" + $("#" + svg).html().substring(4)
                var blob = new Blob([svgs], {
                    type: "image/svg+xml"
                });
                saveAs(blob, svg + ".svg")
            }

            function DownloadSvg(svg, types) {
                let svgs = "<svg xmlns=\"http://www.w3.org/2000/svg\"      xmlns:xlink=\"http://www.w3.org/1999/xlink\"" + $("#" + svg).html().substring(4)
                $.ajax({
                    url: "@routes.BlockController.downloadSvg",
                    type: "post",
                    dataType: "json",
                    data: {
                        svg: svgs,
                        types: types,
                        name:svg
                    },
                    success: function (data) {
                        window.open(`/COADB/synteny/download?path=${data}&name=${svg}&types=${types}`)
                    }
                })
            }


            function getComparison() {
                let species = $("#species").val();
                let chr = $("#chr").val();
                $.post("/COADB/synteny/getComparison?species=" + species + "&chr=" + chr, (data) => {
                    if ($("#blocksForm").data("formValidation") !== undefined) {
                        $("#blocksForm").data("formValidation").destroy();
                    }
                    let html = ""
                    if (data.length === 0) {
                        html = `<span style='color: red'>No species for comparison!</span>`
                    } else {
                        $.each(data, (i, v) => {
                            html += `
                            <div class="form-check">
                                <label class="form-check-label">
                                    <input type='checkbox' name='db[]' value='${v[0]}' class="db">${v[1]}<i class="input-helper"></i>
                                </label>
                            </div>`
                        })
                    }
                    $("#dbBox").html(html);
                    formValidation()
                })
            }

            function getChr() {
                let species = $("#species").val()
                console.log(species)
                $.post("/COADB/synteny/getChr?species=" + species, (data) => {
                    $("#chr").empty().select2({data: data})
                    getComparison()
                })
            }

            function DisData() {

                $.each($(`#species1 option`), (i, v) => {
                    $(v).removeAttr("disabled")
                })

                $.each($(`#species2 option`), (i, v) => {
                    $(v).removeAttr("disabled")
                })

                let select1 = $("#species1").val()
                let select2 = $("#species2").val()
                $(`#species1 option[value=${select2}]`).attr("disabled", "disabled")
                $(`#species2 option[value=${select1}]`).attr("disabled", "disabled")
            }

            function DisData2() {

                $.each($(`#species1-1 option`), (i, v) => {
                    $(v).removeAttr("disabled")
                })

                $.each($(`#species2-1 option`), (i, v) => {
                    $(v).removeAttr("disabled")
                })

                let select1 = $("#species1-1").val()
                let select2 = $("#species2-1").val()
                $(`#species1-1 option[value=${select2}]`).attr("disabled", "disabled")
                $(`#species2-1 option[value=${select1}]`).attr("disabled", "disabled")
            }

            function formValidation() {
                $('#blocksForm').formValidation({
                    framework: 'bootstrap',
                    icon: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        'db[]': {
                            validators: {
                                notEmpty: {
                                    message: 'This is not be empty!'
                                }
                            }
                        }
                    }
                });
                $('#form').formValidation({
                    framework: 'bootstrap',
                    icon: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        'blockId': {
                            validators: {
                                notEmpty: {
                                    message: 'This is not be empty!'
                                }
                            }
                        }
                    }
                });


            }

            function SearchByBlockId() {
                let form = $("#form");
                let fv = form.data("formValidation");
                form.formValidation("revalidateField", "blockId")
                fv.validate();
                if (fv.isValid()) {
                    let index = MyTable.prototype.runningIcon();
                    let blockId = $("#blockId").val()
                    $.post("/COADB/synteny/validBlockIdExist?blockId=" + blockId, (data) => {
                        layer.close(index)

                        if (data.valid === "false") {
                            swal("Error", "Can not find block ID: " + blockId, "error")
                        } else {
                            window.open("/COADB/synteny/syntenyInfoPage/" + data.id[0]);
                        }
                    })

                }

            }

            function GetBlock(value, row) {
                return `<a href="/COADB/synteny/syntenyInfoPage/${row.id}" target="_blank">${value}</a>`
            }

            function GetSpecies1(value, row) {
                return `<div><a href="/COADB/browse/genomePage/${row.querySpecies}" target="_blank">${row.qSpecies}</a></div><div>${row.query}:${row.queryStart}-${row.queryEnd}</div>`
            }

            function GetSpecies2(value, row) {
                return `<div><a href="/COADB/browse/genomePage/${row.refSpecies}" target="_blank">${row.rSpecies}</a></div><div>${row.ref}:${row.refStart}-${row.refEnd}</div>`
            }

            function getEg() {
                $(`#blockId`).val("Camellia_lanceoleosa_vs_Coleifera_1");
                $("#form").formValidation("revalidateField", "blockId")
            }


            function getDotPlot() {

                let index = MyTable.prototype.runningIcon();

                $.ajax({
                    url: "@routes.BlockController.getDotPlotBySpecies",
                    type: "post",
                    data: {
                        "species1": $("#species1").val(),
                        "species2": $("#species2").val()
                    },
                    success: (data) => {

                        let pos = $.parseJSON(data.pos)
                        let series = $.parseJSON(data.series)


                        $("#dot-box").empty()
                        var dafaultMenuItem = Highcharts.getOptions().exporting.buttons.contextButton.menuItems;
                        Highcharts.chart('dot-box', {
                            chart: {
                                type: 'scatter',
                                height: 800,
                                width: 1000
                            },
                            boost: {
                                useGPUTranslations: true,
                                usePreAllocated: true
                            },
                            credits: {
                                enabled: false
                            },
                            exporting: {
                                sourceWidth: 1000,
                                allowHTML: true,
                                buttons: {
                                    contextButton: {
                                        text: 'Save'
                                    }
                                }

                                /*                              buttons: {

                                                                  contextButton: {
                                                                      enabled:false
                                                                  },
                                                                  exportButton: {
                                                                      align:"left",
                                                                      text: 'Download SVG ',
                                                                      width: 120,
                                                                      theme:{
                                                                          fill: '#007bff',
                                                                          stroke: 'silver',
                                                                          r: 4,

                                                                          style:{
                                                                              color:"white"
                                                                          },
                                                                          states: {
                                                                              hover: {
                                                                                  fill: '#41739D',
                                                                                  style: {
                                                                                      color: 'white'
                                                                                  }
                                                                              }
                                                                          }

                                                                      },
                                                                      // Use only the download related menu items from the default context button
                                                                      onclick: function () {
                                                                          this.exportChart({type: "image/svg+xml"})
                                                                      }
                                                                  },

                                                              }*/
                            },
                            xAxis: {
                                min: 0,
                                gridLineWidth: 1,//网格线宽度
                                showFirstLabel: false,//是否展示第一个x轴下标
                                gridLineDashStyle: "Dash",
                                tickPixelInterval: 40,
                                title: {
                                    text: data.xT
                                },
                                labels: {
                                    x: -25,
                                    formatter: function () {
                                        return data.xAxis[this.value - 1]
                                    }
                                }
                            },
                            yAxis: {
                                min: 0,
                                max: data.yAxis.length,
                                allowDecimals: false,
                                title: {
                                    text: data.yT
                                },
                                gridLineWidth: 1,//网格线宽度
                                gridLineDashStyle: "Dash",
                                tickPixelInterval: 40,
                                showFirstLabel: false,//是否展示第一个x轴下标
                                labels: {
                                    y: 25,
                                    formatter: function () {
                                        return data.yAxis[this.value - 1]
                                    }
                                }
                            },

                            title: {
                                text: `Dot Plot between ` + data.xT + ' and ' + data.yT
                            },
                            legend: {
                                enabled: false
                            },
                            plotOptions: {
                                series: {

                                    marker: {
                                        radius: 1.5,
                                        symbol: 'circle'
                                    },
                                    events: {
                                        click: function () {
                                            console.log("this")
                                            console.log(this)
                                        }
                                    },
                                    tooltip: {
                                        followPointer: false,
                                        pointFormatter: function () {
                                            let x = this.x + "-" + this.y;
                                            let json = pos[x].split("\t").join("<br/>")
                                            return `${json} `
                                        }
                                    }
                                }
                            },
                            series: series
                        });
                        const $result = $("#d-result");
                        $result.show()
                        let target_top = $result.offset().top - 80;
                        $("html,body").animate({scrollTop: target_top}, 800);

                        layer.close(index);
                    }
                })
            }

            function getCircosPlot() {

                let index = MyTable.prototype.runningIcon();

                $.ajax({
                    url: "@routes.BlockController.getComparisonAllResult",
                    type: "post",
                    data: {
                        "species1": $("#species1-1").val(),
                        "species2": $("#species2-1").val()
                    },
                    success: (data) => {
                        $("#c-result-box").empty();



                        let html = `
                                         <div style="position: absolute;width: 1000px;text-align: right">
    <div class="download-btn" style="position: absolute;z-index: 1000;right:0;">

    <button type="button"><i class="fa fa-align-justify" style="color:#666666"></i> Save</button>


        <div class="highcharts-contextmenu" style="display: none;text-align: left" >
        <ul class="highcharts-menu" style="list-style: none; margin: 0px; padding: 5px 0px; box-shadow: rgb(136, 136, 136) 3px 3px 10px; border: 1px solid rgb(153, 153, 153); background: rgb(255, 255, 255);">
            <li class="highcharts-menu-item" onclick="DownloadSvg('circos','png')" >Download PNG image</li>
<li class="highcharts-menu-item" onclick="DownloadSvg('circos','jpeg')" >Download JPEG image</li>
<li class="highcharts-menu-item" onclick="DownloadSvg('circos','pdf')" >Download PDF document</li>
<li class="highcharts-menu-item" onclick="DownloadSvgFn('circos')" >Download SVG vector image</li></ul></div>

    </div> </div>

                                             <div id="circos"></div>
                                             <table id="circos-table" class="table table-bordered" data-pagination="true" data-page-list="[10, 25, 50, 100]">
                                                 <thead>
                                                    <tr>
                                                        <th data-field='name' data-formatter="GetBlock">Block ID</th>
                                                        <th data-field='s1' data-formatter="GetSpecies1">Species1 (location)</th>
                                                        <th data-field='s2' data-formatter="GetSpecies2">Species2 (location)</th>
                                                        <th data-field='score' >Score</th>
                                                        <th data-field='eValue' >E_Value</th>
                                                        <th data-field='n' >N</th>
                                                    </tr>
                                                </thead>
                                            </table>
                                        `


                        $("#c-result-box").html(html);

                        $(".download-btn").click(function () {
                            let s = $(this).find(".highcharts-contextmenu").is(":hidden");

                            if (s) {
                                $(this).find(".highcharts-contextmenu").show()
                            } else {
                                $(this).find(".highcharts-contextmenu").hide()
                            }

                        })

                        let datas = [
                            {
                                "canvas": "circos",
                                "ideoCollection": data.result.collection,
                                "linkCollection": data.result.ur
                            }
                        ];
                        circos(datas)
                        $("#circos-table").bootstrapTable({data: data.result.table})


                        const $result = $("#c-result");
                        $result.show()
                        let target_top = $result.offset().top - 80;
                        $("html,body").animate({scrollTop: target_top}, 800);

                        layer.close(index)
                    }
                })
            }



    </script>

}

@ByBlocks = {
    <form class="registration-form col-sm-12 my-form" id="blocksForm">

        <div class="row">
            @components.species("3", "6", onchange = "getChr()")
            @components.chr("3", "6", "getComparison()")

            <div class="col-md-12  form-group my-position">
                <label class="col-sm-3 my-position-title">Choose species for comparison:</label>
                <div class="col-sm-8">
                    <div style="display: flex;
                        flex-wrap: wrap" id="dbBox"></div>
                    <input type="checkbox" name="db[]" style="display: none" />
                </div>
            </div>

        </div>

        <div class="col-md-12 form-group">
            <label class="col-sm-3"></label>
            <button type="button" class="btn my-btn" style="width: 200px" onclick="Search()">
                Search</button>
        </div>
    </form>

    <div id="b-result" style="display: none;">
        <hr>
        <h5>Result:</h5>

        <div id="result-box"></div>

    </div>

}

@ByBlockId = {
    <form class="registration-form col-sm-12 my-form" id="form">

        <div class="row">
            <div class="col-sm-12 form-group my-position">
                <label class="col-sm-3 my-position-title">Block ID :</label>
                <div class="col-sm-6">
                    <input class="form-control" type="text" name="blockId" id="blockId" />
                    <p style="margin-bottom: 0" >
                        e.g.,&nbsp;<a href="javascript:void(0);" onclick="getEg()"><em class="egCrics">
                        Example</em></a></p>
                </div>
            </div>
        </div>

        <div class="col-md-12 form-group">
            <label class="col-sm-3"></label>
            <button type="button" class="btn my-btn" style="width: 200px" onclick="SearchByBlockId()">
                Search</button>
        </div>
    </form>


}

@BySpecies = {
    <form class="registration-form col-sm-12 my-form" id="speciesForm">

        <div class="row">
            @components.species("3", "6", id = "species1", onchange = "DisData()", title = "Species1")
            @components.species("3", "6", id = "species2", onchange = "DisData()", title = "Species2")

        </div>

        <div class="col-md-12 form-group">
            <label class="col-sm-3"></label>
            <button type="button" class="btn my-btn" style="width: 200px" onclick="getDotPlot()">
                Search</button>
        </div>
    </form>
    <div id="d-result" style="display: none;">
        <hr>
        <h5>Result:</h5>

        <div id="dot-box" style="display: flex;
            justify-content: center"></div>
    </div>
}

@CircosBySpecies = {
    <form class="registration-form col-sm-12 my-form" id="circosForm">

        <div class="row">
            @components.species("3", "6", id = "species1-1", onchange = "DisData2()", title = "Species1")
            @components.species("3", "6", id = "species2-1", onchange = "DisData2()", title = "Species2")

        </div>

        <div class="col-md-12 form-group">
            <label class="col-sm-3"></label>
            <button type="button" class="btn my-btn" style="width: 200px" onclick="getCircosPlot()">
                Search</button>
        </div>
    </form>

    <div id="c-result" style="display: none;">
        <hr>
        <h5>Result:</h5>

        <div id="c-result-box"></div>

    </div>
}

